<?php

namespace App\Jobs;

use App\Contract\OrderType;
use App\Http\Service\DeviceService;
use App\Model\Agent;
use App\Model\AgentAmountLog;
use App\Model\Bill;
use App\Model\BillPay;
use App\Model\Device;
use App\Model\Message;
use App\Model\UserAmountLog;
use App\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CheckBleOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $order_no;
    private $hand;
    public $tries = 1;
    public $timeout = 10;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($order_no, $hand = 1)
    {
        $this->order_no = $order_no;
        $this->hand = $hand;
        //因为要导入大文件 需要很久时间
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            Redis::setex('CHECK_CACHE_'.$this->order_no,60*60*24*3,1);
            Log::info('queue-check:'.$this->order_no);
            $order = \App\Model\Order::query()->where('order_no',$this->order_no)->first();
            if($order && $order->recharge_status != 3){
                $deviceModel = Device::query()->where('id', $order->device_id)->first();
                $user = User::query()->where('id',$order->user_id)->first();
                 if($deviceModel->du > ($order->device_du+$order->du*0.2)){
                     $order->recharge_status = 3;
                     $order->description = '蓝牙表系统结算';
                     $order->save();
                     $service = app()->make(DeviceService::class);
                     $service->addRechargeLog($order->device_id, $order->du, $order->pay_amt,$user,$order->paid_at);
                     $amount = $order->pay_amt - $order->fee;
                     if ($order->device_id) {
                         $deviceModel = Device::query()->where('id', $order->device_id)->first();
                         $deviceModel->recharge_callback_at = Carbon::now()->toDateTimeString();
                         $deviceModel->save();
                         if ($deviceModel->agent_id) {
                             $agentModel = Agent::query()->where('id', $deviceModel->agent_id)->first();
                             $allRate = number_format($order->pay_amt * (Agent::MAX_RATE / 100), 2,'.', '');
                             try {
                                 if ($agentModel->pid) {
                                     $firstAgent = Agent::query()->where('id', $agentModel->pid)->first();
                                     $agentType = $firstAgent->type;
                                 } else {
                                     $firstAgent = $agentModel;
                                     $agentType = $agentModel->type;
                                 }
                                 if ($agentType == 2) {
                                     $firstFee = $deviceFee = number_format($firstAgent->service * $order->du, 2, '.', '');
                                     if($firstAgent->rate > 0){
                                         $deviceProfit = $amount*($firstAgent->rate/100);
                                     }else{
                                         $deviceProfit = 0;
                                     }
                                     $amount -= $deviceFee;
                                     if ($agentModel->pid && $firstAgent->service > 0) {
                                         $secondFee = number_format(($firstAgent->service * $agentModel->service / 100) * $order->du, 2, '.', '');
                                         if($secondFee+$deviceProfit > $deviceFee){
                                             $secondFee = $deviceFee-$deviceProfit;
                                         }
                                         $firstFee = number_format($deviceFee - $secondFee, 2, '.', '');
                                         if ($secondFee > 0) {
                                             $agentModel->amount += $secondFee;
                                             $agentModel->total_amount += $secondFee;
                                             $agentModel->total_fee += $order->pay_amt;
                                             $agentModel->save();
                                             AgentAmountLog::create([
                                                 'agent_id' => $agentModel->id,
                                                 'type' => $order->type,
                                                 'amount' => $secondFee,
                                                 'order_id' => $order->id,
                                                 'device_amount'=>$deviceFee,
                                                 'log' => '设备管理费收入',
                                                 'agent_type' => 2
                                             ]);
                                         }
                                     }
                                     if ($firstFee > 0) {
                                         $firstFee-=$deviceProfit;
                                         $firstAgent->amount += $firstFee;
                                         $firstAgent->total_amount += $firstFee;
                                         $firstAgent->total_fee += $order->pay_amt;
                                         $firstAgent->save();
                                         AgentAmountLog::create([
                                             'agent_id' => $firstAgent->id,
                                             'type' => $order->type,
                                             'amount' => $firstFee,
                                             'device_amount'=>$deviceFee,
                                             'order_id' => $order->id,
                                             'log' => '设备管理费收入',
                                             'agent_type' => 2
                                         ]);
                                     }
                                 } else {
                                     if ($agentModel->rate) {
                                         if ($agentModel->rate > 0.3) {
                                             $agentModel->rate = 0.3;
                                         }
                                         $secAmount = number_format($order->pay_amt * $agentModel->rate / 100, 2, '.', '');
                                         AgentAmountLog::create([
                                             'agent_id' => $agentModel->id,
                                             'type' => $order->type,
                                             'amount' => $secAmount,
                                             'order_id' => $order->id,
                                             'log' => '电费充值（线上）分润收入'
                                         ]);

                                         $agentModel->amount += $secAmount;
                                         $agentModel->total_amount += $secAmount;
                                         $agentModel->total_fee += $order->pay_amt;
                                         $agentModel->save();
                                         $firstAmount = $allRate - $secAmount;
                                         if ($firstAmount > 0 && $agentModel->pid) {
                                             AgentAmountLog::create([
                                                 'agent_id' => $firstAgent->id,
                                                 'type' => $order->type,
                                                 'amount' => $firstAmount,
                                                 'order_id' => $order->id,
                                                 'log' => '电费充值（线上）分润收入'
                                             ]);
                                             $firstAgent->amount += $secAmount;
                                             $firstAgent->total_amount += $secAmount;
                                             $firstAgent->total_fee += $order->pay_amt;
                                             $firstAgent->save();
                                         }
                                     }
                                 }
                             } catch (\Exception $e) {

                             }
                         }
                     }
                     // 写入账单
                     // 生成电费账单
                     $bill = new Bill();
                     if($order->device->type == 2){
                         $type = OrderType::WATER;
                         $title = '水费充值:'.$order->du.'吨';
                     }else{
                         $type = OrderType::ELECTRIC;
                         $title = '电费充值:'.$order->du.'度';
                     }
                     $check = Bill::where('type',$type)
                         ->where('paid_at',$order->paid_at)
                         ->where('device_id',$order->device_id)
                         ->first();
                     if($check){
                         Log::info('已有该账单无需重复操作----'.$order->id);
                         return ;
                     }
                     $bill->fill([
                         'business_id' => $order->business_id,
                         'mobile' => $order->user->mobile,
                         'house_id' => $order->house_id,
                         'device_id' => $order->device_id,
                         'title' => $title,
                         'amount' => $amount,
                         'type' => $type,
                         'is_paid' => 1,
                         'paid_at' => $order->paid_at,
                         'target_id'=>$order->id,
                         //'pay_date' => now()->toDateString(),
                     ]);
                     $bill->save();
                     // 写入房东余额
                     $fd = $order->business->user;
                     $fd->amount += $amount;
                     $fd->total_amount += $amount;
                     $fd->save();
                     if($fd->sub_1 == 1 && $fd->sub_status == 1 && $fd->openid){
                         dispatch(new PushMessage($order,$fd->openid));
                     }
                     // 写入账户明细
                     UserAmountLog::create([
                         'user_id' => $fd->id,
                         'type' => $order->type,
                         'amount' => $amount,
                         'order_id' => $order->id,
                         'log' => '线上支付收入'
                     ]);
                     // 写入房东消息
                     Message::create([
                         'user_id'=> $fd->id,
                         'title' => '账单支付成功通知',
                         'content' => '支付项目：' . $order->goods_desc . ' <br> 到账金额：￥' . $amount
                     ]);

                     $billPay = new BillPay();
                     $billPay->fill([
                         'sn' => $order->order_no,
                         'bill_id' => $bill->id,
                         'amount' => $amount,
                         'payment' => $order->pay_channel == 'wx_lite' ? 4 : 5,
                         'is_paid' => 1,
                         'paid_at' => $order->paid_at,
                     ]);
                     $billPay->save();
                 }else{
                     if($order->recharge_status == 1){
                         $order->recharge_status = 2;
                         $order->save();
                         $order->setCache();
                         // 增加日志
                         $service = app()->make(DeviceService::class);
                         $service->addRechargeFailLog($order->device_id, $order->du, $order->pay_amt,$order->device_du,$deviceModel->du);
                     }
                 }
            }
            Redis::del('CHECK_CACHE_'.$this->order_no);
        }catch (\Exception $e){
            Redis::del('CHECK_CACHE_'.$this->order_no);
            Log::info($e->getMessage());
        }
    }
}

